﻿using System;
using System.Configuration;

namespace Trackr.Core
{
	/// <summary>
	/// Will read and write with MyTime.app.config
	/// </summary>
	public class ConfigUtility
	{
		private Configuration _conf;
		private static ConfigUtility _instance;
		private static object _lock = new object();
		public static ConfigUtility Instance
		{
			get
			{
				lock (_lock)
				{
					if (_instance != null)
						return _instance;
					return _instance = new ConfigUtility();
				}
			}
		}
		private ConfigUtility()
		{
			_conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
		}

		/// <summary>
		/// Gets or sets a value from the config file
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string this[string key]
		{
			get
			{
				return Get(key);
			}
			set
			{
				Set(key, value);
			}
		}

		/// <summary>
		/// Gets the value from appConfig
		/// </summary>
		/// <param name="key">The key of the appConfig section</param>
		/// <returns>a string value</returns>
		public string Get(string key)
		{
			var obj = _conf.AppSettings.Settings[key];
			if (obj == null)
				return null;
			if (string.IsNullOrEmpty(obj.Value))
				return null;
			return obj.Value;
		}
		/// <summary>
		/// Will set a value in a appConfig section
		/// </summary>
		/// <param name="key">The key to set</param>
		/// <param name="value">The value to apply to the key</param>
		public void Set(string key, string value)
		{
			_conf.AppSettings.Settings[key].Value = value;
			_conf.Save();
		}
	}
}
